﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.IO;
using Honestysoft.Baseframework.WebUI;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace Honestysoft.Financing.WebUI.Module.Reports.JSON
{
    /// <summary>
    /// GetR010 的摘要说明
    /// </summary>
    public class GetR010 : IHttpHandler
    {
        #region

        //#region 模拟
        //private WindowsImpersonationContext impersonationContext;

        //private const int LOGON32_LOGON_INTERACTIVE = 2;
        //private const int LOGON32_PROVIDER_DEFAULT = 0;

        //[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        //private static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword,
        //              int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        //[DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
        //private extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);

        //[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        //private static extern bool RevertToSelf();

        //[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        //private extern static bool CloseHandle(IntPtr handle);

        ///// <summary>
        ///// 模拟一个用户
        ///// </summary>
        ///// <param name="userName">用户名</param>
        ///// <param name="password">密码</param>
        ///// <param name="domain">域名/计算机名</param>
        ///// <returns>true 模拟成功，false 模拟失败</returns>
        //public bool ImpersonateUser(string userName, string password, string domain)
        //{
        //    WindowsIdentity wi;
        //    IntPtr token = IntPtr.Zero;
        //    IntPtr tokenDuplicate = IntPtr.Zero;
        //    if (RevertToSelf())
        //    {
        //        if (LogonUser(userName, domain, password,
        //                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
        //        {
        //            if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
        //            {
        //                wi = new WindowsIdentity(tokenDuplicate);
        //                impersonationContext = wi.Impersonate();
        //                if (impersonationContext != null)
        //                {
        //                    CloseHandle(tokenDuplicate);
        //                    CloseHandle(token);
        //                    return true;
        //                }
        //                else
        //                {
        //                    if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate);
        //                    if (token != IntPtr.Zero) CloseHandle(token);
        //                    return false;
        //                }
        //            }
        //            else
        //            {
        //                if (token != IntPtr.Zero) CloseHandle(token);
        //                return false;
        //            }
        //        }
        //        else
        //            return false;
        //    }
        //    else
        //        return false;
        //}

        ///// <summary>
        ///// 取消模拟
        ///// </summary>
        //public void UndoImpersonation()
        //{
        //    impersonationContext.Undo();
        //}
        //#endregion

        //#region 关机
        //[StructLayout(LayoutKind.Sequential, Pack = 1)]
        //private struct TokPriv1Luid
        //{
        //    public int Count;
        //    public long Luid;
        //    public int Attr;
        //}

        //[DllImport("kernel32.dll", ExactSpelling = true)]
        //private static extern IntPtr GetCurrentThread();

        //[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        //private static extern bool OpenThreadToken(IntPtr h, int acc, bool openAsSelf, ref IntPtr phtok);

        //[DllImport("advapi32.dll", SetLastError = true)]
        //private static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);

        //[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        //private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst,
        //             int len, IntPtr prev, IntPtr relen);

        //[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        //private static extern bool ExitWindowsEx(int flg, int rea);

        //[DllImport("advapi32.dll")]
        //private static extern bool InitiateSystemShutdown(string Machinename, string Message,
        //              long Timeout, bool ForceAppsClosed, bool RebootAfterShutdown);

        //private const int SE_PRIVILEGE_ENABLED = 0x00000002;
        //private const int TOKEN_QUERY = 0x00000008;
        //private const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        //private const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        //private const int EWX_LOGOFF = 0x00000000;
        //private const int EWX_SHUTDOWN = 0x00000001;
        //private const int EWX_REBOOT = 0x00000002;
        //private const int EWX_FORCE = 0x00000004;
        //private const int EWX_POWEROFF = 0x00000008;
        //private const int EWX_FORCEIFHUNG = 0x00000010;

        ///// <summary>
        ///// 关机
        ///// </summary>
        ///// <returns></returns>
        //public bool ShutDown()
        //{
        //    bool result;
        //    TokPriv1Luid tp;
        //    //注意:这里用的是GetCurrentThread,而不是GetCurrentProcess
        //    IntPtr hproc = GetCurrentThread();
        //    IntPtr htok = IntPtr.Zero;
        //    //注意:这里用的是OpenThreadToken(打开线程令牌),而不是OpenProcessToken(打开进程令牌)
        //    result = OpenThreadToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
        //                       true, ref htok);
        //    tp.Count = 1;
        //    tp.Luid = 0;
        //    tp.Attr = SE_PRIVILEGE_ENABLED;
        //    result = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
        //    result = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
        //    result = InitiateSystemShutdown("", "", 60, true, false);
        //    return result;
        //}
        //#endregion

        #endregion

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            ////复制模板到新目录，并且重写数据，刷新图表
            //string date = context.Request.Params["Date"];
            //DataTable dt = new Honestysoft.Financing.BusinessLogic.Reports("").GetR010(Convert.ToDateTime(date));          

            //string dir = "Reports/JD";
            //if (!Directory.Exists(context.Server.MapPath(Globals.Home + dir)))
            //{
            //    Directory.CreateDirectory(context.Server.MapPath(Globals.Home + dir));
            //}
            //if (File.Exists(context.Server.MapPath(Globals.Home + dir + "/" + date + ".xls")))
            //{
            //    File.Delete(context.Server.MapPath(Globals.Home + dir + "/" + date + ".xls"));
            //}
            //string templateFileName = context.Server.MapPath(Globals.Home + "Module/Reports/Template/JDTemplate.xls");
            //string outPutFile = context.Server.MapPath(Globals.Home + dir + "/" + date + ".xls");
            //Honestysoft.BaseLibrary.Common.ExcelHelper excelHelper = new BaseLibrary.Common.ExcelHelper(templateFileName, outPutFile);
            //try
            //{
            //    excelHelper.DataTableToExcel(dt, 2, 1, excelHelper.GetSheet(2));
            //    excelHelper.SetChartDataSource(1, "图表 1", 2, "B1", "E" + (1 + dt.Rows.Count).ToString());
            //    excelHelper.OutputExcelFile();
            //    //excelHelper.Quit();
            //    //模拟用户，调用程序，生成swf文件
            //    //string swfFileName = string.Format("{0}.swf",  atObj.Code);
            //    //if (ImpersonateUser("administrator", "wangling800214", "caisp"))
            //    //{
            //    //    Audit.AuditUtils.ExportToSWF(outPutFile, context.Server.MapPath(Globals.Home + dir + "/" + date + ".swf"));
            //    //}
            //    context.Response.Write("1");
            //}
            //catch
            //{
            //    context.Response.Write("0");
            //}
            //finally
            //{
                
            //    excelHelper.Quit();
            //    //模拟用户，调用程序，生成swf文件
            //    ////string swfFileName = string.Format("{0}.swf",  atObj.Code);
            //    //if (ImpersonateUser("administrator", "wangling800214", "caisp"))
            //    //{
            //    //    Audit.AuditUtils.ExportToSWF(outPutFile, context.Server.MapPath(Globals.Home + dir + "/" + date + ".swf"));
            //    //}
            //}

            //context.Response.ContentType = "text/plain";
            ////复制模板到新目录，并且重写数据，刷新图表
            //string date = context.Request.Params["Date"];
            //DataTable dt = new Honestysoft.Financing.BusinessLogic.Reports("").GetR010(Convert.ToDateTime(date));
            //Template.JD jdFile = new Template.JD(date + ".xls");
            //jdFile.InitTargetDir();
            //jdFile.DeleteTargetFile();
            //Honestysoft.BaseLibrary.Common.ExcelHelper excelHelper = new BaseLibrary.Common.ExcelHelper(jdFile.TemplateFileMapPath, jdFile.TargetFileMapPath);
            //try
            //{
            //    excelHelper.DataTableToExcel(dt, 2, 1, excelHelper.GetSheet(2));
            //    excelHelper.SetChartDataSource(1, "图表 1", 2, "B1", "E" + (1 + dt.Rows.Count).ToString());
            //    excelHelper.OutputExcelFile();
            //    context.Response.Write("1");
            //}
            //catch
            //{
            //    context.Response.Write("0");
            //}
            //finally
            //{
            //    excelHelper.Quit();
            //}
            context.Response.ContentType = "text/plain";
            //复制模板到新目录，并且重写数据，刷新图表
            string date = context.Request.Params["Date"];
            DateTime theDate = Convert.ToDateTime(date);
            BusinessLogic.Reports logic = new BusinessLogic.Reports("");
            DataTable dt2 = logic.GetR011(theDate);
            DataView dv = new DataView(dt2);
            dv.Sort = "vSort";
            DataTable dt = dv.ToTable();
            DataTable dtJD = dt.Copy();
            DataTable dtChart = new DataTable();

            dtJD.Columns.Remove("ProjectID");
            dtJD.Columns.Remove("vSort");
            dtJD.Columns.Remove("FCode");
            dtJD.Columns.Remove("P_TZ");
            dtJD.Columns.Remove("P_JDZF");
            dtJD.Columns.Remove("P_ZBJ");
            dtJD.Columns.Remove("ZBJ");
            dtJD.Columns.Remove("GS");
            dtJD.Columns.Remove("AmountS");
            dtJD.Columns.Remove("JD");
            dtJD.Columns.Remove("KcDate");

            dtChart.Columns.Add("SN", typeof(string));
            dtChart.Columns.Add("ProjectName", typeof(string));
            dtChart.Columns.Add("FCode", typeof(string));
            dtChart.Columns.Add("SJDate", typeof(DateTime));
            dtChart.Columns.Add("E1", typeof(string));
            dtChart.Columns.Add("E2", typeof(string));
            dtChart.Columns.Add("SJDay", typeof(int));
            dtChart.Columns.Add("JHDay", typeof(int));
            dtChart.Columns.Add("PlanEndDate", typeof(DateTime));
            dtChart.Columns.Add("EndDate", typeof(DateTime));
            dtChart.Columns.Add("KcDate", typeof(DateTime));

            DataRow newRow = null;
            foreach (DataRow dr in dt.Rows)
            {
                newRow = dtChart.NewRow();
                newRow["SN"] = dr["SN"];
                newRow["ProjectName"] = dr["ProjectName"];
                newRow["FCode"] = dr["FCode"] + " " + dr["ProjectName"];
                newRow["SJDate"] = dr["PlanStartDate"];
                TimeSpan ts = Convert.ToDateTime(dr["EndDate"]).Subtract(Convert.ToDateTime(dr["PlanEndDate"]));
                newRow["SJDay"] = ts.Days;
                newRow["PlanEndDate"] = Convert.ToDateTime(dr["PlanEndDate"]);
                newRow["EndDate"] = Convert.ToDateTime(dr["EndDate"]);
                newRow["KcDate"] = Convert.ToDateTime(dr["KcDate"]);
                dtChart.Rows.Add(newRow);
                newRow = dtChart.NewRow();
                newRow["SN"] = "";
                newRow["SJDate"] = dr["PlanStartDate"];
                ts = Convert.ToDateTime(dr["StartDate"]).Subtract(Convert.ToDateTime(dr["PlanStartDate"]));
                newRow["JHDay"] = ts.Days;
                dtChart.Rows.Add(newRow);
                newRow = dtChart.NewRow();
                newRow["SN"] = "";
                dtChart.Rows.Add(newRow);
            }

            Template.JD jdFile = new Template.JD(date + ".xls");
            jdFile.InitTargetDir();
            jdFile.DeleteTargetFile();
            Honestysoft.BaseLibrary.Common.ExcelHelper excelHelper = new BaseLibrary.Common.ExcelHelper(jdFile.TemplateFileMapPath, jdFile.TargetFileMapPath);
            try
            {
                excelHelper.DataTableToExcel(dtJD, 2, 1, excelHelper.GetSheet(2));
                excelHelper.DataTableToExcel(dtChart, 3, 2, excelHelper.GetSheet(1));
                //excelHelper.SetChartDataSource(1, "图表 1", 2, "B1", "E" + (1 + dt.Rows.Count).ToString());
                //excelHelper.SetChartDataSource(1, "图表 1", 1, "B2", "L" + (2 + dtChart.Rows.Count).ToString());
                Microsoft.Office.Interop.Excel.ChartObject cobj = (Microsoft.Office.Interop.Excel.ChartObject)excelHelper.GetSheet(1).ChartObjects("图表 1");
                Microsoft.Office.Interop.Excel.Series ser1 = (Microsoft.Office.Interop.Excel.Series)cobj.Chart.SeriesCollection(1);
                ser1.XValues = "='计划进度图'!$D$3:$D$" + (2 + dtChart.Rows.Count).ToString();
                ser1.Values = "='计划进度图'!$E$3:$E$" + (2 + dtChart.Rows.Count).ToString();

                Microsoft.Office.Interop.Excel.Series ser2 = (Microsoft.Office.Interop.Excel.Series)cobj.Chart.SeriesCollection(2);
                 ser2.Values = "='计划进度图'!$H$3:$H$" + (2 + dtChart.Rows.Count).ToString();
                Microsoft.Office.Interop.Excel.Series ser3 = (Microsoft.Office.Interop.Excel.Series)cobj.Chart.SeriesCollection(3);
                ser3.Values = "='计划进度图'!$I$3:$I$" + (2 + dtChart.Rows.Count).ToString();
                //cobj.Chart.ChartTitle.Text = theDate.ToString("yyyy年M月") + "项目投资计划完成情况及工程进度和资金拨付比例示意图";
                excelHelper.SetTextBox(1, "TextBox 2", theDate.ToString("yyyy.M.d") + "绘制");
                excelHelper.OutputExcelFile();
                context.Response.Write("1");
            }
            catch
            {
                context.Response.Write("0");
            }
            finally
            {
                excelHelper.Quit();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}